package com.cs2.volunteerpostbackend.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cs2.volunteerpostbackend.po.User;
import com.cs2.volunteerpostbackend.service.UserService;
import com.cs2.volunteerpostbackend.web.dto.RespEntity;
import com.cs2.volunteerpostbackend.web.dto.moment.MomentUserVO;
import com.cs2.volunteerpostbackend.web.dto.user.LoginRequest;
import com.cs2.volunteerpostbackend.web.vo.user.UserInfoVo;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/user/register")
    public RespEntity register(@RequestBody User user) {
        // 检查账号是否已存在
        String account = user.getAccount();
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("account", account);
        if (userService.count(qw) > 0) {
            return RespEntity.error("用户名已存在");
        }

        try {
            // 设置创建时间的时间戳
            user.setCreateTime(new Date().getTime());
            userService.save(user);
            return RespEntity.success("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RespEntity.error("注册失败"+e.getMessage());
        }
    }

    @PostMapping("/auth/login")
    public RespEntity login(@RequestBody LoginRequest loginRequest) {

        String account = loginRequest.getAccount();
        String password = loginRequest.getPassword();

        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("account", account);
        qw.eq("password", password);

        User user = userService.getOne(qw);

        if (user == null) {
            return new RespEntity("400", "用户名或密码错误", null);
        }
        user.setPassword(null);

        // 构建 jwt
        JwtBuilder builder = Jwts.builder();

        // ! JWT 由 header(库自己生成), payload(自己加的东西), signature(签名算法) 组成

        // claims 是自己加的东西的声明
        // setClaims 会直接覆盖所有过往添加的 claims，所以导致了同一个用户申请的 token 完全一致
        builder.setClaims(new HashMap<String, Object>() {{
            put("id", user.getId());
            put("account", user.getAccount());
            put("username", user.getUsername());
            put("role", user.getRole());
            put("create_time", user.getCreateTime());
        }});
        // 后面这些 setId, setIssuedAt, setExpiration, signWith 都是在扩充 claims 表中的内容
        // 所以 setClaims 中的表需要设置可编辑的表
        builder.setId(UUID.randomUUID().toString());
        builder.setIssuedAt(new java.util.Date());
        builder.setExpiration(new Date(System.currentTimeMillis()+1000*60*60*24));
        builder.signWith(SignatureAlgorithm.HS256,"123456");

        String jwtToken = builder.compact();   // 这个是 jwt 凭证
        System.out.println("token:" + jwtToken);

        return new RespEntity("200", "登录成功", Map.of("user", user, "token", jwtToken));
    }

    @PutMapping("/user/update")
    public RespEntity update(@RequestBody User user) {
        if (userService.updateById(user)) {
            System.out.println("用户信息更新成功");
        } else {
            System.out.println("用户信息更新失败");
            return new RespEntity("500", "更新失败", null);
        }

        return new RespEntity("200", "更新成功", null);
    }

    @DeleteMapping("/user/delete")
    public RespEntity delete(@RequestParam String id) {
        if (userService.removeById(id)) {
            System.out.println("用户信息删除成功");
        } else {
            System.out.println("用户信息删除失败");
            return new RespEntity("500", "删除失败", null);
        }

        return new RespEntity("200", "删除成功", null);
    }

    @GetMapping("/user/list")
    public RespEntity getUserList(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size
    ) {
        try {
            // 创建分页对象
            Page<User> page = new Page<>(current, size);
            userService.page(page);

            return new RespEntity("200", "查询成功", page);
        } catch (Exception e) {
            e.printStackTrace();
            return new RespEntity("500", "查询失败: " + e.getMessage(), null);
        }
    }
}
